package com.lyhengtongwl.zqsnews.ui.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.NewsMainNoticeEntity;
import com.lyhengtongwl.zqsnews.entity.UserDeviceBo;
import com.lyhengtongwl.zqsnews.ui.fragment.NewsMMByForwardFragmentNew;
import com.lyhengtongwl.zqsnews.ui.fragment.NewsWithDrawFragment;
import com.lyhengtongwl.zqsnews.ui.fragment.NewsMMByEnlightenFragment;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.NewsBrowserShare;
import com.lyhengtongwl.zqsnews.utils.NewsForwardAnimation;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.PhoneUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.StatusBarUtil;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.entity.MainTabEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.SystemUtils;
import com.lyhengtongwl.zqsnews.utils.UserUtils;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

import static com.lyhengtongwl.zqsnews.App.activities;
import static com.lyhengtongwl.zqsnews.base.Constant.ShareDetail;

public class MainActivity extends BaseActivity {
    //动画部分
    @BindView(R.id.iv_1)
    ImageView iv1;
    @BindView(R.id.iv_2)
    ImageView iv2;
    @BindView(R.id.iv_3)
    ImageView iv3;

    @BindView(R.id.menu_bg)
    View menu_bg;
    @BindView(R.id.img_publish)
    ImageView img_publish;
    @BindView(R.id.frame_layout)
    RelativeLayout frame_layout;
    public static boolean isMenuOpen = false;
    long lastClickTime = 0;//判断是否快速点击
    private CommonTabLayout mTabLayout;
    ArrayList<Fragment> mFragments = new ArrayList<>();
    private int currentTab = 0;
    private List<String> list = new ArrayList<>();
    private List<View> views;
    private List<NewsMainNoticeEntity> mainNoticeEntities = null;

    @Override
    public void setTitleBarColor() {
    }

    @OnClick({R.id.img_publish, R.id.menu_bg, R.id.iv_1, R.id.iv_2, R.id.iv_3

    })
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.img_publish:
                if (!isMenuOpen) {
                    menu_bg.setVisibility(View.VISIBLE);
                    img_publish.setImageResource(R.drawable.icon_collapse_);
                    NewsForwardAnimation.getInstance(this, views, img_publish).showOpenAnim(100);
                } else {
                    menu_bg.setVisibility(View.GONE);
                    img_publish.setImageResource(R.drawable.icon_release_);
                    NewsForwardAnimation.getInstance(this, views, img_publish).showCloseAnim(100);
                }
                break;
            case R.id.menu_bg:
                menu_bg.setVisibility(View.GONE);
                img_publish.setImageResource(R.drawable.icon_release_);
                NewsForwardAnimation.getInstance(this, views, img_publish).showCloseAnim(100);
                break;
            case R.id.iv_1://上传文章
                startActivity(new Intent(this, NewsWebUploadActivity.class));
                menu_bg.setVisibility(View.GONE);
                img_publish.setImageResource(R.drawable.icon_release_);
                NewsForwardAnimation.getInstance(this, views, img_publish).showCloseAnim(100);
                break;
            case R.id.iv_2://我的上传
                startActivity(new Intent(this, NewsMyArticleActivity.class).putExtra("type", "1"));
                menu_bg.setVisibility(View.GONE);
                img_publish.setImageResource(R.drawable.icon_release_);
                NewsForwardAnimation.getInstance(this, views, img_publish).showCloseAnim(100);
                break;
            case R.id.iv_3://我的收藏
                startActivity(new Intent(this, NewsMyArticleActivity.class).putExtra("type", "2"));
                menu_bg.setVisibility(View.GONE);
                img_publish.setImageResource(R.drawable.icon_release_);
                NewsForwardAnimation.getInstance(this, views, img_publish).showCloseAnim(100);
                break;
        }
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onStart() {
        super.onStart();
        switch (mTabLayout.getCurrentTab()) {
            case 0:
                EventBus.getDefault().post("checkEarn");
                break;
            case 1:
                break;
            case 2:
                EventBus.getDefault().post("refreshNew");
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void initData() {
        activities.add(this);
        String[] mTitles = {getString(R.string.msg), getString(R.string.contact), getString(R.string.my)};
        int[] mIconUnSelectIds = {
                R.drawable.icon_forward_unselected, R.drawable.icon_recruit_unselected,
                R.drawable.icon_withdraw_unselected};
        int[] mIconSelectIds = {
                R.drawable.icon_forward_selected, R.drawable.icon_recruit_selected,
                R.drawable.icon_withdraw_selected};
        //tab的标题、选中图标、未选中图标
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        //设置tab的标题、选中图标、未选中图标
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new MainTabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        //初始化数据
        mFragments.add(new NewsMMByForwardFragmentNew());
        mFragments.add(new NewsMMByEnlightenFragment());
        mFragments.add(new NewsWithDrawFragment());
        //给tab设置数据和关联的fragment
        mTabLayout.setTabData(mTabEntities, this, R.id.fl_change, mFragments);
        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 0:
                        frame_layout.setVisibility(View.VISIBLE);
                        StatusBarUtil.setStatusBar(MainActivity.this, false);
                        break;
                    case 1:
                        frame_layout.setVisibility(View.GONE);
                        StatusBarUtil.setStatusBar(MainActivity.this, false);
                        break;
                    case 2:
                        frame_layout.setVisibility(View.GONE);
                        StatusBarUtil.setStatusBar(MainActivity.this, false);
                        break;
                }
                if (!UserUtils.checkLogin() && position != 2) {//用户未登录且不在个人页，记录当前页
                    currentTab = position;
                }
            }

            @Override
            public void onTabReselect(int position) {
                if (!UserUtils.checkLogin() && position != 2) {//用户未登录且不在个人页，记录当前页
                    currentTab = position;
                }
            }
        });
        checkVersion();
        try {
            //获取海报
//            getHB();
            //上传位置信息
//            GPSUtils.getInstance(this).getLocation();
            toastNotice();
            //上传设备信息
            upLoadDeviceMsg();
            //上传通讯录
//            getPhonePermission();
            //弹出红包界面
            String redBag = SPUtils.get(App.getContext(), "redBag", "") + "";
            switch (redBag) {
                case "0"://表示未领取
                    new CenterDialog(R.layout.item_redpacket_1, MainActivity.this).showRedPacket_unOpen();
                    break;
                case "1"://表示已经领取
                    Log.e("redBag", "initData: 已经领取过！");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //检测权限问题
//    private void getPhonePermission() {
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
//                != PackageManager.PERMISSION_GRANTED) {
//        } else {
//            new PhoneUtils(this).upLoadPhones();
//        }
//    }

    //静态内部类handler，防止内存泄漏
    //获取三张海报
//    private void getHB() {
//        Task.getApiService().getShareOr().enqueue(new MyCallback<NewsBaseEntity>(MainActivity.this) {
//            @Override
//            protected void onSuccess(Response<NewsBaseEntity> response) {
//                try {
//                    assert response.body() != null;
//                    list.clear();
//                    if ("1".equals(response.body().getCode())) {
//                        String jsonStr = JSONObject.toJSONString(response.body().getData());
//                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//                        String shareCode = jsonObject.getString("shareCode");
//                        SPUtils.put(App.getContext(), "shareCode", shareCode);
//                        JSONArray jsonArray = jsonObject.getJSONArray("shareImgs");
//                        for (int i = 0; i < jsonArray.size(); i++) {
//                            list.add(jsonArray.get(i).toString());
//                        }
//                        App.hbList.clear();
//                        App.hbList.addAll(list);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            protected void onFailure(Throwable t) {
//
//            }
//        });
//    }
    //获取公告列表

    private void toastNotice() {
        Task.getApiService().toastNotice().enqueue(new MyCallback<NewsBaseEntity>(MainActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    if ("1".equals(response.body().getCode())) {
                        mainNoticeEntities = new ArrayList<>();
                        String jsonStr = JSONObject.toJSONString(response.body().getData());
                        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                        if (jsonArray.size() > 0) {
                            for (int i = 0; i < jsonArray.size(); i++) {
                                NewsMainNoticeEntity newsMainNoticeEntity = new NewsMainNoticeEntity();
                                newsMainNoticeEntity.setContent(jsonArray.getJSONObject(i).getString("content"));
                                newsMainNoticeEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                                newsMainNoticeEntity.setPosition(jsonArray.getJSONObject(i).getInteger("position"));
                                mainNoticeEntities.add(newsMainNoticeEntity);
                            }
                            new CenterDialog(R.layout.item_prompt_notice, MainActivity.this).showPromptNotice(mainNoticeEntities);

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //上传设备信息
    private void upLoadDeviceMsg() {
        UserDeviceBo userDeviceBo = new UserDeviceBo();
        userDeviceBo.setClientName("android");
        userDeviceBo.setClientVersion(android.os.Build.MODEL);
        userDeviceBo.setDeviceId(SPUtils.get(App.getContext(), "uniqueIdentifier", "") + "");
        userDeviceBo.setDeviceName(android.os.Build.BRAND);
        userDeviceBo.setIdfa("");
        userDeviceBo.setIdfv("");
        userDeviceBo.setOsName("android");
        userDeviceBo.setOsVersion(SystemUtils.getOSVersion());
        userDeviceBo.setUserid(Integer.parseInt(SPUtils.get(this, "userId", "0") + ""));
        userDeviceBo.setMarket("android-ks");//下载来源
        Task.getApiService().upLoadDeviceMsg(userDeviceBo).enqueue(new MyCallback<NewsBaseEntity>(MainActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
//                Log.e("uploadDevice", "上传设备信息！");
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //检测系统版本
    private void checkVersion() {
//        Task.getApiService().checkVersion().enqueue(new MyCallback<BaseEntity>(MainActivity.this) {
//            @Override
//            protected void onSuccess(Response<BaseEntity> response) {
//                if ("0".equals(response.body().getCode())) {
//                    String description = response.body().getResult().getString("description");
//                    String linkUrl = response.body().getResult().getString("link");
//                    String type = response.body().getResult().getString("type");
//                    String version_romate = response.body().getResult().getString("version");
//                    String version_local = SystemUtils.getLocalVersionName(App.getContext());
//                    if (SystemUtils.compareVersion(version_local, version_romate) < 0) {
//                        new CenterDialog(R.layout.updatapk_dialog, MainActivity.this)
//                                .showUpdatePrompt(getApplicationContext(), description, type, linkUrl);
//                    }
//                }
//            }
//
//            @Override
//            protected void onFailure(Throwable t) {
//
//            }
//        });
    }

    @Override
    public void initView() {
        //初始化组件
        mTabLayout = findViewById(R.id.tl);
        views = new ArrayList<>();
        views.add(iv1);
        views.add(iv2);
        views.add(iv3);
//        初始化QQ分享
//        myIUiListener = new MyIUiListener();
    }

    @Override
    public void setListen() {
    }

    /**
     * 处理快速点击造成的重复生成界面影响
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        int tab = intent.getIntExtra("tab", 0);
        if (tab == 0) {
            frame_layout.setVisibility(View.VISIBLE);
        } else {
            frame_layout.setVisibility(View.GONE);
        }
        switch (tab) {
            case 0:
            case 2:
                mTabLayout.setCurrentTab(tab);
                break;
            case 1:
                String categoryId = intent.getStringExtra("actionUrl");
                toCategory(categoryId);
                break;
        }
    }

    /**
     * 判断是否快速点击(时间间隔在300ms以内，就算快速点击)
     *
     * @return
     */
    private boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= 300;
    }

    /**
     * 获取底部控件
     *
     * @return
     */
    public CommonTabLayout getTabLayout(int i) {
        if (i == 0) {
            frame_layout.setVisibility(View.VISIBLE);
        } else {
            frame_layout.setVisibility(View.GONE);
        }
        return mTabLayout;
    }

    /**
     * 获取当前页
     */
    public int getCurrentTab() {
        return currentTab;
    }

    /**
     * 跳转到分类页面
     *
     * @param categoryId
     */
    private void toCategory(String categoryId) {
        mTabLayout.setCurrentTab(1);
        Bundle bundle = new Bundle();
        bundle.putString("categoryId", categoryId);
        if (mFragments.get(1) != null) {
            mFragments.get(1).setArguments(bundle);
        }
    }

    /**
     * 拦截返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK://返回键
                new CenterDialog(R.layout.prompt_quit_dialog, MainActivity.this).showQuitPrompt("确认要退出应用？");
                break;
            case KeyEvent.KEYCODE_MENU://菜单键
                break;
            case KeyEvent.KEYCODE_HOME://home键
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //没有点击条目直接点返回
        if (data == null) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息**
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);

                Uri muri = Uri.parse("smsto:" + contacts[1]);
                Intent it = new Intent(Intent.ACTION_SENDTO, muri);
                it.putExtra("sms_body", ShareDetail + AppConfig.getInstance(App.getContext()).get("redBagUrl") + "?shareCode=" + SPUtils.get(App.getContext(), "shareCode", ""));
                startActivity(it);
            }
        }).start();
        super.onActivityResult(requestCode, resultCode, data);
    }

    //回调中所用到的方法
    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象**
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标**
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名**
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码**
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

}

